package handlers

import (
	"fmt"
	"restaurant-system/config"
	"restaurant-system/internal/models"
	"restaurant-system/internal/services"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 获取用户聊天列表
func GetUserChats(c *gin.Context) {
	var sessions []models.ChatSession
	if err := config.DB.
		Preload("User").
		Preload("Messages", func(db *gorm.DB) *gorm.DB {
			return db.Order("created_at desc")
		}).
		Order("updated_at desc").
		Where("user_id != 1").
		Find(&sessions).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取聊天列表失败"})
		return
	}

	type ChatResponse struct {
		ID              uint      `json:"id"`
		UserID          uint      `json:"user_id"`
		Username        string    `json:"username"`
		Avatar          string    `json:"avatar"`
		LastMessage     string    `json:"lastMessage"`
		LastMessageTime time.Time `json:"lastMessageTime"`
		UnreadCount     int       `json:"unread"`
		Online          bool      `json:"online"`
		LastLoginAt     time.Time `json:"lastLoginAt"`
		Points          int       `json:"points"`
		Phone           string    `json:"phone"`
		Email           string    `json:"email"`
	}

	var response []ChatResponse
	for _, session := range sessions {
		// 计算管理员的未读消息数（用户发送的未读消息）
		unreadCount := 0
		for _, msg := range session.Messages {
			if msg.SenderID != 1 && msg.Status != "read" {
				unreadCount++
			}
		}

		response = append(response, ChatResponse{
			ID:              session.ID,
			UserID:          session.UserID,
			Username:        session.User.Username,
			Avatar:          session.User.Avatar,
			LastMessage:     session.LastMessage,
			LastMessageTime: session.UpdatedAt,
			UnreadCount:     unreadCount,
			Online:          false,
			LastLoginAt: func() time.Time {
				if session.User.LastLoginAt != nil {
					return *session.User.LastLoginAt
				}
				return time.Time{}
			}(),
			Points: session.User.Points,
			Phone:  session.User.Phone,
			Email:  session.User.Email,
		})
	}

	c.JSON(200, gin.H{"chats": response})
}

// 获取聊天记录
func GetChatMessages(c *gin.Context) {
	userID := c.Param("id")
	fmt.Printf("Getting messages for userID: %s\n", userID)

	// 先获取用户的会话
	var session models.ChatSession
	if err := config.DB.Where("user_id = ? AND type = ?", userID, "customer_service").First(&session).Error; err != nil {
		fmt.Printf("Error finding session: %v\n", err)
		c.JSON(200, gin.H{"messages": []models.ChatMessage{}})
		return
	}

	// 打印会话信息
	fmt.Printf("Found session: ID=%d, UserID=%d\n", session.ID, session.UserID)

	var messages []models.ChatMessage
	if err := config.DB.
		Debug().
		Table("chat_messages").
		Where("session_id = ? AND deleted_at IS NULL", session.ID).
		Order("created_at asc").
		Find(&messages).Error; err != nil {
		fmt.Printf("Error finding messages: %v\n", err)
		c.JSON(500, gin.H{"error": "获取聊天记录失败"})
		return
	}

	// 打印找到的消息
	fmt.Printf("Found %d messages\n", len(messages))
	for _, msg := range messages {
		fmt.Printf("Message: ID=%d, SessionID=%d, SenderID=%d, Content=%s\n",
			msg.ID, msg.SessionID, msg.SenderID, msg.Content)
	}

	type MessageResponse struct {
		ID      uint      `json:"id"`
		Content string    `json:"content"`
		Type    string    `json:"type"`
		Sender  string    `json:"sender"`
		Status  string    `json:"status"`
		Read    bool      `json:"read"`
		Time    time.Time `json:"time"`
	}

	var response []MessageResponse
	for _, msg := range messages {
		senderType := "user"
		if msg.SenderID == 1 {
			senderType = "admin"
		}

		// 消息是否已读：对于管理员来说，用户发送的消息才需要标记已读状态
		isRead := true
		if msg.SenderID != 1 {
			isRead = msg.Status == "read"
		}

		response = append(response, MessageResponse{
			ID:      msg.ID,
			Content: msg.Content,
			Type:    msg.Type,
			Sender:  senderType,
			Status:  msg.Status,
			Read:    isRead,
			Time:    msg.CreatedAt,
		})
	}

	// 将用户发送的消息标记为已读
	if err := config.DB.Model(&models.ChatMessage{}).
		Where("session_id = ? AND sender_id != 1 AND status != ?", session.ID, "read").
		Update("status", "read").Error; err != nil {
		fmt.Printf("Update message status error: %v\n", err)
	}

	c.JSON(200, gin.H{"messages": response})
}

// 发送消息
func SendAdminMessage(c *gin.Context) {
	fmt.Printf("Received admin message request\n")
	var req struct {
		UserID  uint   `json:"user_id" binding:"required"`
		Content string `json:"content" binding:"required"`
		Type    string `json:"type" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Printf("Binding JSON error: %v\n", err)
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	fmt.Printf("Request data: %+v\n", req)

	// 获取用户的会话
	var session models.ChatSession
	result := config.DB.Where("user_id = ? AND type = ?", req.UserID, "customer_service").First(&session)
	if result.Error != nil {
		c.JSON(400, gin.H{"error": "找不到用户会话"})
		return
	}

	fmt.Printf("Found user session: ID=%d, UserID=%d\n", session.ID, session.UserID)

	// 创建消息
	message := models.ChatMessage{
		SessionID: session.ID,
		SenderID:  1,
		Content:   req.Content,
		Type:      req.Type,
		Status:    "sent", // 用户端显示未读
	}
	fmt.Printf("Creating admin message in session %d: %+v\n", session.ID, message)

	if err := config.DB.Create(&message).Error; err != nil {
		fmt.Printf("Create message error: %v\n", err)
		c.JSON(500, gin.H{"error": "发送消息失败"})
		return
	}

	// 更新会话最后消息
	session.LastMessage = req.Content
	if err := config.DB.Save(&session).Error; err != nil {
		fmt.Printf("Update session error: %v\n", err)
		c.JSON(500, gin.H{"error": "更新会话失败"})
		return
	}

	fmt.Printf("Message sent successfully\n")
	c.JSON(200, gin.H{"message": "发送成功"})
}

// 发布系统通知
func PublishNotification(c *gin.Context) {
	var req struct {
		Title   string `json:"title" binding:"required"`
		Content string `json:"content" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	// 获取所有用户
	var users []models.User
	if err := config.DB.Find(&users).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取用户列表失败"})
		return
	}

	// 为每个用户创建通知
	for _, user := range users {
		notification := models.Notification{
			UserID:  user.ID,
			Title:   req.Title,
			Content: req.Content,
			Type:    "system",
			Status:  "unread",
		}

		if err := config.DB.Create(&notification).Error; err != nil {
			continue
		}
	}

	c.JSON(200, gin.H{"message": "发布成功"})
}

// 用户获取聊天记录
func GetMessages(c *gin.Context) {
	userID, _ := c.Get("userID")
	if userID == nil {
		c.JSON(401, gin.H{"error": "未授权"})
		return
	}

	var session models.ChatSession
	if err := config.DB.Where("user_id = ?", userID).First(&session).Error; err != nil {
		session = models.ChatSession{
			UserID: userID.(uint),
			Type:   "customer_service",
		}
		if err := config.DB.Create(&session).Error; err != nil {
			c.JSON(500, gin.H{"error": "创建会话失败"})
			return
		}
	}

	var messages []models.ChatMessage
	if err := config.DB.
		Where("session_id = ?", session.ID).
		Preload("Session").
		Order("created_at asc").
		Find(&messages).Error; err != nil {
		c.JSON(500, gin.H{"error": "获取消息失败"})
		return
	}

	fmt.Printf("Found messages: %+v\n", messages)

	type MessageResponse struct {
		ID      uint      `json:"id"`
		Content string    `json:"content"`
		Type    string    `json:"type"`
		Sender  string    `json:"sender"`
		Status  string    `json:"status"`
		Read    bool      `json:"read"`
		Time    time.Time `json:"time"`
	}

	var response []MessageResponse
	for _, msg := range messages {
		senderType := "user"
		if msg.SenderID == 1 {
			senderType = "admin"
		}

		// 消息是否已读：对于管理员来说，用户发送的消息才需要标记已读状态
		isRead := true
		if msg.SenderID != 1 {
			isRead = msg.Status == "read"
		}

		response = append(response, MessageResponse{
			ID:      msg.ID,
			Content: msg.Content,
			Type:    msg.Type,
			Sender:  senderType,
			Status:  msg.Status,
			Read:    isRead,
			Time:    msg.CreatedAt,
		})
	}

	fmt.Printf("Response messages: %+v\n", response)

	// 标记消息为已读
	if err := config.DB.Model(&models.ChatMessage{}).
		Where("session_id = ? AND sender_id = ?", session.ID, 1).
		Update("status", "read").Error; err != nil {
		// 忽略错误继续执行
	}

	// 重置未读计数
	session.UnreadCount = 0
	config.DB.Save(&session)

	c.JSON(200, gin.H{"messages": response})
}

// 用户发送消息
func SendMessage(c *gin.Context) {
	userID, _ := c.Get("userID")
	fmt.Printf("Sending message for userID: %v\n", userID)

	if userID == nil {
		c.JSON(401, gin.H{"error": "未授权"})
		return
	}

	var req struct {
		Content string `json:"content" binding:"required"`
		Type    string `json:"type" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Printf("Binding JSON error: %v\n", err)
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	fmt.Printf("Request data: %+v\n", req)

	// 获取或创建会话
	var session models.ChatSession
	result := config.DB.Where("user_id = ?", userID).First(&session)
	if result.Error != nil {
		fmt.Printf("Creating new session for user %v\n", userID)
		session = models.ChatSession{
			UserID: userID.(uint),
			Type:   "customer_service",
		}
		if err := config.DB.Create(&session).Error; err != nil {
			fmt.Printf("Create session error: %v\n", err)
			c.JSON(500, gin.H{"error": "创建会话失败"})
			return
		}
	}

	// 创建用户消息
	message := models.ChatMessage{
		SessionID:  session.ID,
		SenderID:   userID.(uint),
		SenderType: "user",
		Content:    req.Content,
		Type:       req.Type,
		Status:     "sent",
	}

	if err := config.DB.Create(&message).Error; err != nil {
		c.JSON(500, gin.H{"error": "发送消息失败"})
		return
	}

	// 触发AI客服回复
	aiService := services.NewAIService()
	if aiMessage := aiService.HandleMessage(session.ID, req.Content); aiMessage != nil {
		// 更新会话最后消息
		session.LastMessage = aiMessage.Content
		config.DB.Save(&session)
	}

	c.JSON(200, gin.H{"message": "发送成功"})
}

func getSenderType(senderID uint) string {
	if senderID == 1 {
		return "admin"
	}
	return "user"
}

// 获取未读消息数
func GetUnreadCount(c *gin.Context) {
	userID, _ := c.Get("userID")
	var session models.ChatSession

	if err := config.DB.Where("user_id = ?", userID).First(&session).Error; err != nil {
		c.JSON(200, gin.H{"count": 0})
		return
	}

	c.JSON(200, gin.H{"count": session.UnreadCount})
}
